package com.winit.openapi.isp.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.erp.spi.ebay.EbayOrderService;
import com.winit.erp.spi.ebay.command.EbayOrderSerchKeyCommand;
import com.winit.erp.spi.ebay.vo.EbayOrderDetailVo;
import com.winit.erp.spi.ebay.vo.EbayOrderVo;
import com.winit.erp.spi.product.ProductService;
import com.winit.erp.spi.product.command.QueryProductCommand;
import com.winit.erp.spi.product.vo.Product;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.oms.spi.isp.command.order.ISPOrderCreateCommand;
import com.winit.oms.spi.isp.common.BatchResult;
import com.winit.oms.spi.isp.vo.ISPOrder;
import com.winit.oms.spi.isp.vo.ISPOrderLine;
import com.winit.oms.spi.isp.vo.ISPOrderMerchandise;
import com.winit.oms.spi.vo.CreateOrderResult;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitRuleService;
import com.winit.pms.spi.winit.command.WinitProductQueryCommand;
import com.winit.pms.spi.winit.command.WinitRuleQueryCommand;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.pms.spi.winit.vo.WinitRule;

/**
 * EBay创建ISP发货信息
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hou 	1.0  		2015-7-20 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/isp/ebayDelivery")
public class ISPEbayDeliveryController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ISPEbayDeliveryController.class);

    @Resource
    private ISPOrderService     ispOrderService;
    @Resource
    private ContractService     agreementService;
    @Resource
    private WinitProductService productService;
    @Resource
    private ProductService      erpProductService;
    @Resource
    private WinitRuleService    winitRuleService;
    @Resource
    private EbayOrderService    ebayOrderService;

    /**
     * 创建ISP订单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();

        List<ISPOrder> orderList = new ArrayList<ISPOrder>();
        //解析数据
        resolveData(obj, orderList);

        // 组装command
        ISPOrderCreateCommand command = new ISPOrderCreateCommand();
        command.setCtx(CommandContext.getContext());
        command.setOrderList(orderList);

        // 调用接口创建订单
        BatchResult result = ispOrderService.batchCreateISPOrder(command);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccess());
        data.put("failedCount", result.getFailed());
        responseMsg.setData(data);
        return SUCCESS;
    }

    private void resolveData(Object obj, List<ISPOrder> orderList) {
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            if (!json.containsKey("ebayList") && !json.containsKey("winitProductCode")) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
            }
            JSONArray ebaylist = json.getJSONArray("ebayList");
            for (Object o : ebaylist) {
                // 创建订单json
                JSONObject childjson = new JSONObject();
                // 设置卖家网站传入的参数
                childjson.put("winitProductCode", json.getString("winitProductCode"));
                childjson.put("warehouseCode", json.getString("warehouseCode"));
                childjson.put("warehouseName", json.getString("warehouseName"));
                childjson.put("dispatchType", json.getString("dispatchType"));
                childjson.put("shipperAddrCode", json.getString("shipperAddrCode"));
                childjson.put("source", json.getString("source"));

                JSONObject tobj = (JSONObject) o;
                // 设置卖家订单号
                childjson.put("refNo", tobj.getString("refNo"));
                queryProductInfo(childjson, tobj.getLong("wtEbayOrderId"));
                // 校验参数
                validCreateISPOrder(childjson);
                // 构建ISP订单结构
                ISPOrder ispOrder = buildISPOrder(childjson);
                // 设置ebay订单id
                ispOrder.setWtEbayOrderId(tobj.getLong("wtEbayOrderId"));
                // 加入集合中
                orderList.add(ispOrder);
            }

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
    }

    /**
     * 暂存ISP订单,提交到未完成订单中
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/save")
    public String save(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();

        List<ISPOrder> orderList = new ArrayList<ISPOrder>();

        int failNum = 0;// 失败数量
        int successNum = 0;// 成功数量
        //解析数据
        resolveData(obj, orderList);

        for (ISPOrder ispOrder : orderList) {
            try {
                List<ISPOrder> tempOrderList = new ArrayList<ISPOrder>();
                tempOrderList.add(ispOrder);
                // 组装command
                ISPOrderCreateCommand command = new ISPOrderCreateCommand();
                command.setCtx(CommandContext.getContext());
                command.setOrderList(tempOrderList);

                // 调用接口创建订单
                CreateOrderResult result = ispOrderService.saveISPOrderTemporary(command);

                logger.info("saveISPOrderTemporary orderNo " + result.getOrderNo());
                // 修改ebay订单状态为已发货
                EbayOrderSerchKeyCommand ebayCommand = new EbayOrderSerchKeyCommand();
                ebayCommand.setCtx(command.getCtx());
                ebayCommand.setWtEbayOrderId(ispOrder.getWtEbayOrderId());
                ebayOrderService.updateEbayOrderByID(ebayCommand);
                successNum++;
            } catch (Exception e) {
                failNum++;
                e.printStackTrace();
                logger.error("保存isp订单失败" + e.toString(), e);
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", successNum);
        data.put("failedCount", failNum);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 获取ebay订单商品信息 TODO Add comments here.
     * 
     * @param json
     */
    private void queryEbayOrderInfo(JSONObject basejson, JSONObject pack, Long wtEbayOrderId) {
        // 查询ebay订单信息
        EbayOrderSerchKeyCommand ebayCommand = new EbayOrderSerchKeyCommand();
        ebayCommand.setWtEbayOrderId(wtEbayOrderId);
        EbayOrderVo ebayOrderVo = ebayOrderService.queryEbayOrderByID(ebayCommand);

        if (ebayOrderVo == null) {
            throw new ApiException(ErrorCode.GFS_EBAYORDER_NOTFIND, wtEbayOrderId);
        }
        // 买家姓名
        basejson.put("buyerName", ebayOrderVo.getBuyerFullname());

        // 买家电话
        if (ebayOrderVo.getBuyerPhoneNumber() != null) {
            basejson.put("buyerContactNo", ebayOrderVo.getBuyerPhoneNumber());
        } else {
            // 为空显示 0 bug 14063
            basejson.put("buyerContactNo", "0");
        }

        // 买家mail
        basejson.put("buyerEmail", ebayOrderVo.getBuyerEmail());

        // 买家邮编
        basejson.put("buyerZipCode", ebayOrderVo.getBuyerPostcode());

        // 买家国家
        basejson.put("buyerCountry", ebayOrderVo.getBuyerCountry());

        // 买家州或省
        if (ebayOrderVo.getBuyerState() != null) {
            basejson.put("buyerState", ebayOrderVo.getBuyerState());
        } else {
            // 为空显示 城市名称 bug 14063
            basejson.put("buyerState", ebayOrderVo.getBuyerCity());
        }

        // 买家城市
        basejson.put("buyerCity", ebayOrderVo.getBuyerCity());

        // 买家街道1
        basejson.put("buyerAddress1", ebayOrderVo.getBuyerAddress1());

        // 买家街道2
        basejson.put("buyerAddress2", ebayOrderVo.getBuyerAddress2());

        // 买家门牌号
        // obj =
        // setMerchandiseValue("buyerHouseNo",ebayOrderVo.getBuyerAddress2());

        // 卖家id
        basejson.put("ebaySellerId", ebayOrderVo.getSellerUserid());

        JSONArray merchandiseList = new JSONArray();
        // 获取商品信息
        List<EbayOrderDetailVo> ebayOrderDetailVos = ebayOrderVo.getEbayOrderDetailVos();
        for (EbayOrderDetailVo deailVo : ebayOrderDetailVos) {

            // 获取申报品名
            QueryProductCommand erpcommand = new QueryProductCommand();
            // 获取SKU
            erpcommand.setValue(deailVo.getSku());
            erpcommand.setInCountryCode(ebayOrderVo.getBuyerCountry());
            erpcommand.setCtx(CommandContext.getContext());
            List<Product> products = erpProductService.queryProductByValue(erpcommand); 
            JSONObject merchandise = new JSONObject();
            try {
                // 申报品名 中文
                merchandise.put("declaredNameCn", products.get(0).getName());
    
                // 申报品名 英文
                merchandise.put("declaredNameEn", products.get(0).getEname());
    
                // 申报价值
                merchandise.put("declaredValue", products.get(0).getValuedeclared().setScale(2, BigDecimal.ROUND_HALF_UP));
            } catch (Exception e) {
                if(products != null && products.size() > 0)
                {
                    // 申报品名 中文
                    merchandise.put("declaredNameCn", products.get(0).getName());
        
                    // 申报品名 英文
                    merchandise.put("declaredNameEn", products.get(0).getEname());
                }
                else
                {
                    // 申报品名 中文
                    merchandise.put("declaredNameCn", "");
        
                    // 申报品名 英文
                    merchandise.put("declaredNameEn", "");
                }
                // 申报价值
                merchandise.put("declaredValue", 0);
                logger.error("get erpProduct is null or Valuedeclared is null", e);
            }
            // merchandise.put("declaredValue",new
            // BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 交易号
            merchandise.put("transactionID", deailVo.getTansactionid());

            // 商品id
            merchandise.put("itemID", deailVo.getItemid());

            merchandiseList.add(merchandise);

        }

        // 加入包裹中
        pack.put("merchandiseList", merchandiseList);
    }

    /**
     * 获取产品相关信息 TODO Add comments here.
     * 
     * @param json
     */
    private void queryProductInfo(JSONObject json, Long wtEbayOrderId) {
        // 获取产品
        WinitProductQueryCommand command = new WinitProductQueryCommand();
        command.setCode(json.getString("winitProductCode"));
        WinitProduct winitProduct = productService.queryProduct(command);
        if (winitProduct == null) {
            throw new ApiException(ErrorCode.GFS_WINITPRODUCTCODE_NOTFIND, json.getString("winitProductCode"));
        }
        // 获取产品规则
        WinitRuleQueryCommand rcommand = new WinitRuleQueryCommand();
        rcommand.setWinitProductId(winitProduct.getWinitProductId());
        List<WinitRule> rules = winitRuleService.findWinitRuleByProductId(rcommand);

        if (rules == null || rules.size() == 0) {
            throw new ApiException(ErrorCode.GFS_WINITPRODUCT_RULE_NOTFIND, winitProduct.getName());
        }
        // 设置长宽高体积
        JSONObject pack = new JSONObject();
        for (WinitRule re : rules) {
            if ("Weight".equals(re.getRuleAttribute())) {
                setPackageValue("weight", re, 0.1, pack, 4);
            } else if ("Length".equals(re.getRuleAttribute())) {
                setPackageValue("length", re, 10, pack, 2);
            } else if ("Hight".equals(re.getRuleAttribute())) {
                setPackageValue("height", re, 10, pack, 2);
            } else if ("Width".equals(re.getRuleAttribute())) {
                setPackageValue("width", re, 10, pack, 2);
            }
        }

        // 获取订单信息
        queryEbayOrderInfo(json, pack, wtEbayOrderId);

        JSONArray packageList = new JSONArray();
        packageList.add(pack);

        json.put("packageList", packageList);

    }

    /**
     * 设置包裹长宽高 TODO Add comments here.
     * 
     * @param re
     * @return
     */
    private void setPackageValue(String key, WinitRule re, double defaultValue, JSONObject packageList, int length) {
        BigDecimal value;
        if (re.getRuleMinValue() != null) {
            value = re.getRuleMinValue();
        } else if (re.getRuleMaxValue() != null) {
            value = re.getRuleMaxValue();
        } else {
            value = BigDecimal.valueOf(defaultValue);
        }
        // 保留小数位
        value = value.setScale(length, BigDecimal.ROUND_HALF_UP);
        packageList.put(key, value);
    }

    // 效验用户是不是isp用户
    public void checkIspRight() {
        ContractCommand command = new ContractCommand();
        command.setBusiType("ISP");
        command.setBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        boolean rightStatus = agreementService.isOpenContract(command);

        if (!rightStatus) {
            throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
        }
    }

    private void validCreateISPOrder(JSONObject json) {

        // shipperAddrCode
        ValidateUtil.validNotNull(json, "shipperAddrCode");
        ValidateUtil.validMaxLength(json, "shipperAddrCode", 8);
        validISPOrder(json);
    }

    private void validISPOrder(JSONObject json) {
        // refNo
        ValidateUtil.validMaxLength(json, "refNo", 60);

        // dispatchType
        ValidateUtil.validNotNull(json, "dispatchType");
        validDispatchType(json);
        String dispatchType = json.getString("dispatchType");
        // warehouseCode
        if (dispatchType.equals("S")) {
            ValidateUtil.validNotNull(json, "warehouseCode");
            ValidateUtil.validMaxLength(json, "warehouseCode", 30);
        } else {
            ValidateUtil.validMaxLength(json, "warehouseCode", 30);
        }
        // winitProductCode
        ValidateUtil.validNotNull(json, "winitProductCode");
        ValidateUtil.validMaxLength(json, "winitProductCode", 50);

        /************** ebay ********************/
        // ebaySellerId
        ValidateUtil.validMaxLength(json, "ebaySellerId", 50);
        /****************** buyer *******************/
        // buyerName
        ValidateUtil.validNotNull(json, "buyerName");
        ValidateUtil.validMaxLength(json, "buyerName", 50);
        // buyerContactNo
        ValidateUtil.validNotNull(json, "buyerContactNo");
        ValidateUtil.validMaxLength(json, "buyerContactNo", 50);
        // buyerEmail
        ValidateUtil.validMaxLength(json, "buyerEmail", 60);
        ValidateUtil.validEmail(json, "buyerEmail");
        // buyerZipCode
        ValidateUtil.validNotNull(json, "buyerZipCode");
        ValidateUtil.validMaxLength(json, "buyerZipCode", 10);
        // buyerCountry
        ValidateUtil.validNotNull(json, "buyerCountry");
        ValidateUtil.validMaxLength(json, "buyerCountry", 50);
        // buyerState
        ValidateUtil.validNotNull(json, "buyerState");
        ValidateUtil.validMaxLength(json, "buyerState", 50);
        // buyerCity
        ValidateUtil.validNotNull(json, "buyerCity");
        ValidateUtil.validMaxLength(json, "buyerCity", 50);
        // buyerAddress1
        ValidateUtil.validNotNull(json, "buyerAddress1");
        ValidateUtil.validMaxLength(json, "buyerAddress1", 100);
        // buyerAddress2
        ValidateUtil.validMaxLength(json, "buyerAddress2", 100);

        // buyerHouseNo
        ValidateUtil.validMaxLength(json, "buyerHouseNo", 10);

        /****************** package *******************/
        // packageList
        ValidateUtil.validNotNull(json, "packageList");
        ValidateUtil.validList(json, "packageList");
        JSONArray packageList = json.getJSONArray("packageList");
        for (Object obj : packageList) {
            JSONObject pack = (JSONObject) obj;
            // weight
            if (pack.containsKey("weight")) {
                ValidateUtil.validNotNull(pack, "weight");
                positiveNumber(pack, "weight");
                ValidateUtil.validBigDecimal(pack, "weight");
                // 如果超过4位小数直接截取，保留4位
                round(pack, 4, "weight");
                ValidateUtil.validatePrecision(pack, "weight", 4, 4);
            }
            // length
            if (pack.containsKey("length")) {
                ValidateUtil.validNotNull(pack, "length");
                positiveNumber(pack, "length");
                ValidateUtil.validBigDecimal(pack, "length");
                ValidateUtil.validatePrecision(pack, "length", 4, 2);
            }
            // width
            if (pack.containsKey("width")) {
                ValidateUtil.validNotNull(pack, "width");
                positiveNumber(pack, "width");
                ValidateUtil.validBigDecimal(pack, "width");
                ValidateUtil.validatePrecision(pack, "width", 4, 2);
            }
            // height
            if (pack.containsKey("height")) {
                ValidateUtil.validNotNull(pack, "height");
                positiveNumber(pack, "height");
                ValidateUtil.validBigDecimal(pack, "height");
                ValidateUtil.validatePrecision(pack, "height", 4, 2);
            }

            if (pack.containsKey("merchandiseList")) {
                /********* merchandiseList 商品列表 ***********/
                JSONArray merchandiseList = pack.getJSONArray("merchandiseList");
                for (Object o : merchandiseList) {
                    JSONObject merchandise = (JSONObject) o;
                    // transactionID
                    if (merchandise.containsKey("transactionID")) {
                        ValidateUtil.validMaxLength(merchandise, "transactionID", 30);
                    }
                    // itemID
                    if (merchandise.containsKey("itemID")) {
                        ValidateUtil.validMaxLength(merchandise, "itemID", 30);
                    }
                    // declaredValue
                    if (merchandise.containsKey("declaredValue")) {
                        //ValidateUtil.validNotNull(merchandise, "declaredValue");
                        //positiveNumber(merchandise, "declaredValue");
                        //ValidateUtil.validBigDecimal(merchandise, "declaredValue");
                        // ValidateUtil.validMaxLength(merchandise,
                        // "declaredValue",
                        // 10);
                        //ValidateUtil.validatePrecision(merchandise, "declaredValue", 8, 2);
                    }
                    // declaredName 中文和英文校验
                    if (merchandise.containsKey("declaredNameCn")) {
                        //ValidateUtil.validNotNull(merchandise, "declaredNameCn");
                        ValidateUtil.validMaxLength(merchandise, "declaredNameCn", 100);
                    }

                    if (merchandise.containsKey("declaredNameEn")) {
                        //ValidateUtil.validNotNull(merchandise, "declaredNameEn");
                        ValidateUtil.validMaxLength(merchandise, "declaredNameEn", 100);
                    }
                    /*if (merchandise.containsKey("declaredNameEn")) {
                        // 非中文校验
                        if (!match("[^\u4e00-\u9fa5]+", merchandise.getString("declaredNameEn"))) {
                            // throw new ApiException(ErrorCode.FIELD_CN,
                            // merchandise.getString("declaredNameEn"));
                            throw new ApiException(ErrorCode.FIELD_CN, "declaredNameEn");
                        }
                    }*/
                }
            }
        }
    }

    /**
     * 校验发货方式是否符合规则
     */
    private void validDispatchType(JSONObject json) {
        String dispatchType = json.getString("dispatchType");
        if (!ApiConstant.DISPATCH_TYPE_SET.contains(dispatchType)) {
            throw new ApiException(ErrorCode.DISPATCHTYPE_VALUE_ERROR, dispatchType);
        }
    }

    private ISPOrder buildISPOrder(JSONObject json) {
        ISPOrder ispOrder = new ISPOrder();

        /**************************** ispOrder ***********************/
        if (json.containsKey("refNo")) {
            ispOrder.setSellerOrderNo(json.getString("refNo").trim());
        }
        if (json.containsKey("winitProductCode")) {
            ispOrder.setWinitProductCode(json.getString("winitProductCode").trim());
        }
        if (json.containsKey("warehouseCode")) {
            ispOrder.setWarehouseCode(json.getString("warehouseCode").trim());
        }
        if (json.containsKey("warehouseName")) {
            ispOrder.setWarehouseName(json.getString("warehouseName"));
        }
        if (json.containsKey("warehouseID")) {
            ispOrder.setWarehouseID(json.getLong("warehouseID"));
        }
        if (json.containsKey("dispatchType")) {
            ispOrder.setDispatchType(json.getString("dispatchType"));
        }
        /**************************** buyer ***************************/
        if (json.containsKey("buyerName")) {
            ispOrder.setBuyerFullname(json.getString("buyerName").trim());
        }
        if (json.containsKey("buyerContactNo")) {
            ispOrder.setBuyerContactNumber(json.getString("buyerContactNo").trim());
        }
        if (json.containsKey("buyerEmail")) {
            ispOrder.setBuyerEmail(json.getString("buyerEmail"));
        }
        if (json.containsKey("buyerZipCode")) {
            ispOrder.setBuyerPostcode(json.getString("buyerZipCode").trim());
        }
        if (json.containsKey("buyerCountry")) {
            ispOrder.setBuyerCountry(json.getString("buyerCountry").trim());
        }
        if (json.containsKey("buyerState")) {
            ispOrder.setBuyerState(json.getString("buyerState").trim());
        }
        if (json.containsKey("buyerCity")) {
            ispOrder.setBuyerCity(json.getString("buyerCity").trim());
        }
        if (json.containsKey("buyerAddress1")) {
            ispOrder.setBuyerAddress1(json.getString("buyerAddress1"));
        }
        if (json.containsKey("buyerAddress2")) {
            ispOrder.setBuyerAddress2(json.getString("buyerAddress2") == null ? "" : json.getString("buyerAddress2"));
        }
        if (json.containsKey("buyerHouseNo")) {
            ispOrder.setHouseNo(json.getString("buyerHouseNo"));
        }
        if (json.containsKey("source")) {
            ispOrder.setSource(json.getString("source").trim());
        }

        /*
         * if (json.containsKey("shipperAddrId")) {
         * ispOrder.setShipperAddrId(json.getInteger("shipperAddrId")); }
         */
        if (json.containsKey("shipperAddrCode")) {
            ispOrder.setShipperAddrCode(json.getString("shipperAddrCode"));
        }
        if (json.containsKey("ebaySellerId")) {
            ispOrder.setEbaySellerId(json.getString("ebaySellerId"));
        }

        /****************************** ispOrderLine **************************/
        List<ISPOrderLine> orderLineList = new ArrayList<ISPOrderLine>();
        List<ISPOrderMerchandise> merchandiseList = new ArrayList<ISPOrderMerchandise>();
        ISPOrderMerchandise ispOrderMerchandise = null;
        ISPOrderLine ispOrderLine = null;
        if (json.containsKey("packageList")) {
            JSONArray packageList = json.getJSONArray("packageList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                ispOrderLine = new ISPOrderLine();
                if (pack.containsKey("weight")) {
                    ispOrderLine.setGrossWeight(pack.getBigDecimal("weight"));
                }
                if (pack.containsKey("length")) {
                    ispOrderLine.setLength(pack.getBigDecimal("length"));
                }
                if (pack.containsKey("width")) {
                    ispOrderLine.setWidth(pack.getBigDecimal("width"));
                }
                if (pack.containsKey("height")) {
                    ispOrderLine.setHeight(pack.getBigDecimal("height"));
                }
                if (pack.containsKey("merchandiseList")) {
                    JSONArray merlist = pack.getJSONArray("merchandiseList");
                    /****************************** ISPOrderMerchandise **************************/
                    if (merlist != null) {
                        for (Object o : merlist) {
                            JSONObject mer = (JSONObject) o;
                            ispOrderMerchandise = new ISPOrderMerchandise();
                            if (mer.containsKey("transactionID")) {
                                ispOrderMerchandise.setTransactionId(mer.getString("transactionID"));
                            }
                            if (mer.containsKey("itemID")) {
                                ispOrderMerchandise.setItemId(mer.getString("itemID"));
                            }
                            if (mer.containsKey("declaredValue")) {
                                ispOrderMerchandise.setDeclaredValue(mer.getBigDecimal("declaredValue"));
                            }
                            // 申报品名（中文）
                            if (mer.containsKey("declaredNameCn")) {
                                ispOrderMerchandise.setMerchandiseName(mer.getString("declaredNameCn").trim());
                            }
                            // 申报品名（英文）
                            if (mer.containsKey("declaredNameEn")) {
                                ispOrderMerchandise.setMerchandiseNameEN(mer.getString("declaredNameEn").trim());
                            }
                            merchandiseList.add(ispOrderMerchandise);
                        }
                    }
                }
                ispOrderLine.setMerchandiseList(merchandiseList);
                orderLineList.add(ispOrderLine);
            }
        }
        CommandContext ctx = CommandContext.getContext();
        // String source = (String) ctx.get(ApiConstant.API_SOURCE);
        // 设置其他信息，从上下文取得
        // ispOrder.setSource(source);
        ispOrder.setPlatform("eBay");
        ispOrder.setBpartnerId(Integer.parseInt(ctx.getUserId()));
        ispOrder.setBpartnerName(ctx.getUsername());
        ispOrder.setOrganizationId(ctx.getOrgId().intValue());

        ispOrder.setOrderLineList(orderLineList);
        return ispOrder;
    }

    // 效验重量价格大于0
    public void positiveNumber(JSONObject json, String key) {
        if (isExistValue(json, key) && ValidateUtil.isBigDecimal(json.getString(key))) {
            BigDecimal bd = new BigDecimal(json.getString(key));
            if (bd.compareTo(new BigDecimal("0")) <= 0) {
                throw new ApiException(ErrorCode.FIELD_INPUT_ERROR, key);
            }
        }
    }

    // 效验大于0,批量导入提示
    public void positiveNumberImport(JSONObject json, String key, String xmlKye) {
        if (isExistValue(json, key) && ValidateUtil.isBigDecimal(json.getString(key))) {
            BigDecimal bd = new BigDecimal(json.getString(key));
            if (bd.compareTo(new BigDecimal("0")) <= 0) {
                throw new ApiException(ErrorCode.FIELD_INPUT_ERROR, xmlKye);
            }
        }

    }

    // 判断非必填字段是否有值
    public boolean isExistValue(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            return !"".equals(jsonObject.getString(key).trim());
        }
        return false;
    }

    /**
     * @param regex 正则表达式字符串
     * @param str 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    private void round(JSONObject json, int scale, String field) {
        if (json.containsKey(field)) {
            Object weight = json.get(field);
            if (weight != null && StringUtils.isNotBlank(weight.toString())) {
                String s = weight.toString();
                BigDecimal bd = new BigDecimal(s);
                bd = bd.setScale(4, RoundingMode.HALF_UP);

                json.put(field, bd.toString());
            }
        }
    }
}
